﻿using System;
using System.IO;
using System.Net;
using System.Text;
using log4net;
using System.Configuration;

namespace Eff.Net
{
    /// <summary>
    /// FTP上传文件
    /// </summary>
    public class FtpHerlper
    {
        //Upload("192.168.217.41", "/aa/bb/cc7/5/", "e:\\44.jpg", "ff", "123");
        private static readonly string _ftpServerIp;
        private static readonly string _ftpUserId;
        private static readonly string _ftpPassword;
        private static readonly ILog _log;

        static FtpHerlper()
        {
            _log = LogManager.GetLogger(typeof(FtpHerlper));
            _ftpServerIp = ConfigurationManager.AppSettings["FtpServerIp"];
            _ftpUserId = ConfigurationManager.AppSettings["FtpUserId"];
            _ftpPassword = ConfigurationManager.AppSettings["FtpPassword"];
        }

        /// <summary>
        /// ftp上传
        /// </summary>
        /// <param name="ftpServerIp">ftp服务器ip</param>
        /// <param name="path">ftp目录路径</param>
        /// <param name="filename">文件名</param>
        /// <param name="ftpUserId">ftp账户</param>
        /// <param name="ftpPassword">ftp密码</param>
        /// <returns></returns>
        private static bool Upload(string ftpServerIp, string path, string filename, string ftpUserId, string ftpPassword)
        {
            //创建目录
            MakeAllDirectory(ftpServerIp, path, ftpUserId, ftpPassword);

            FileInfo fileInf = new FileInfo(filename);

            string uri = "ftp://" + ftpServerIp + path + fileInf.Name;

            // 根据uri创建FtpWebRequest对象
            var reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));

            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(ftpUserId, ftpPassword);

            // 默认为true，连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;

            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 指定数据传输类型
            reqFTP.UseBinary = true;

            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;

            // 缓冲大小设置为2kb
            int buffLength = 2048;

            byte[] buff = new byte[buffLength];

            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();

                // 每次读文件流的2kb
                int contentLen = fs.Read(buff, 0, buffLength);

                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // 关闭两个流
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                _log.Error("ftp上传失败", ex);
                return false;
            }
            return true;
        }

        private static void MakeAllDirectory(string ftpServerIP, string path, string ftpUserId, string ftpPassword)
        {
            string[] tem = path.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
            if (tem.Length == 0) return;

            var pathTem = new StringBuilder(tem.Length + 1);
            pathTem.Append("ftp://" + ftpServerIP + "/");
            // bool res = false;
            foreach (var directory in tem)
            {
                pathTem.Append(directory + "/");
                UpMakeDirectory(ftpUserId, ftpPassword, pathTem.ToString());
            }
            //return true;
        }

        private static void UpMakeDirectory(string ftpUserID, string ftpPassword, string uploadUrl)
        {
            FtpWebResponse uploadResponse = null;
            try
            {
                var uploadRequest =
                    (FtpWebRequest)WebRequest.Create(new Uri(uploadUrl));
                uploadRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                // ftp用户名和密码
                uploadRequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                uploadResponse =
                    (FtpWebResponse)uploadRequest.GetResponse();
            }
            catch
            {
                // log.Error("ftp上传错误，远程创建目录失败！," + ex.Message);
                if (uploadResponse != null)
                {
                    uploadResponse.Close();
                }
            }
            if (uploadResponse != null)
            {
                uploadResponse.Close();
            }
        }

        /// <summary>
        /// ftp服务器上传文件
        /// </summary>
        /// <param name="path">文件目录</param>
        /// <param name="filename">文件名</param>
        /// <returns></returns>
        public static bool Upload(string path, string filename)
        {
            //创建目录
            MakeAllDirectory(_ftpServerIp, path, _ftpUserId, _ftpPassword);

            var fileInf = new FileInfo(filename);

            string uri = "ftp://" + _ftpServerIp + path + fileInf.Name;

            // 根据uri创建FtpWebRequest对象
            var reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));

            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);

            // 默认为true，连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;

            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

            // 指定数据传输类型
            reqFTP.UseBinary = true;

            // 上传文件时通知服务器文件的大小
            reqFTP.ContentLength = fileInf.Length;

            // 缓冲大小设置为2kb
            const int buffLength = 2048;

            var buff = new byte[buffLength];

            // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
            FileStream fs = fileInf.OpenRead();
            try
            {
                // 把上传的文件写入流
                Stream strm = reqFTP.GetRequestStream();

                // 每次读文件流的2kb
                int contentLen = fs.Read(buff, 0, buffLength);

                // 流内容没有结束
                while (contentLen != 0)
                {
                    // 把内容从file stream 写入 upload stream
                    strm.Write(buff, 0, contentLen);

                    contentLen = fs.Read(buff, 0, buffLength);
                }

                // 关闭两个流
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                _log.Error("ftp上传错误，远程上传文件失败！," + ex.Message);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 删除ftp服务器文件
        /// </summary>        
        /// <param name="filePath">文件路径</param>        
        /// <returns></returns>
        public static bool Delete(string filePath)
        {
            string uri = "ftp://" + _ftpServerIp + filePath;

            // 根据uri创建FtpWebRequest对象
            var reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(uri));
            // ftp用户名和密码
            reqFTP.Credentials = new NetworkCredential(_ftpUserId, _ftpPassword);
            // 默认为true，连接不会被关闭
            // 在一个命令之后被执行
            reqFTP.KeepAlive = false;
            // 指定执行什么命令
            reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

            try
            {
                var respone = (FtpWebResponse)reqFTP.GetResponse();
                if (respone != null) respone.Close();

                return true;
            }
            catch (Exception ex)
            {
                _log.Error("ftp删除错误，远程删除文件失败！," + ex.Message);
                return false;
            }
        }

    }
}


